import React, { useState, useEffect } from 'react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line } from 'recharts'
import { X, TrendingUp, Clock, FileText, Hash, Type } from 'lucide-react'

interface DocumentAnalyticsProps {
  isOpen: boolean
  onClose: () => void
  content: string
  title: string
}

interface AnalyticsData {
  wordCount: number
  characterCount: number
  characterCountNoSpaces: number
  paragraphCount: number
  sentenceCount: number
  lineCount: number
  readingTime: number
  speakingTime: number
  complexity: {
    avgWordsPerSentence: number
    avgCharsPerWord: number
    vocabularySize: number
    readabilityScore: number
  }
  structure: {
    headings: number
    lists: number
    links: number
    images: number
    codeBlocks: number
    quotes: number
  }
  emotions: {
    positive: number
    negative: number
    neutral: number
  }
  writingTime: {
    estimated: number
    actual?: number
  }
}

const DocumentAnalytics: React.FC<DocumentAnalyticsProps> = ({
  isOpen,
  onClose,
  content,
  title
}) => {
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null)
  const [activeTab, setActiveTab] = useState<'overview' | 'structure' | 'readability' | 'trends'>('overview')

  useEffect(() => {
    if (isOpen && content) {
      const analyticsData = analyzeDocument(content)
      setAnalytics(analyticsData)
    }
  }, [isOpen, content])

  const analyzeDocument = (text: string): AnalyticsData => {
    // Basic counts
    const words = text.split(/\s+/).filter(word => word.length > 0)
    const wordCount = words.length
    const characterCount = text.length
    const characterCountNoSpaces = text.replace(/\s/g, '').length
    const paragraphs = text.split(/\n\n+/).filter(p => p.trim().length > 0)
    const paragraphCount = paragraphs.length
    const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0)
    const sentenceCount = sentences.length
    const lines = text.split('\n')
    const lineCount = lines.length

    // Time estimates
    const readingTime = Math.ceil(wordCount / 200) // 200 WPM average
    const speakingTime = Math.ceil(wordCount / 150) // 150 WPM average speaking

    // Complexity analysis
    const avgWordsPerSentence = sentenceCount > 0 ? wordCount / sentenceCount : 0
    const avgCharsPerWord = wordCount > 0 ? characterCountNoSpaces / wordCount : 0
    const uniqueWords = new Set(words.map(w => w.toLowerCase()))
    const vocabularySize = uniqueWords.size

    // Simple readability score (based on sentence length and word length)
    const avgSentenceLength = avgWordsPerSentence
    const avgWordLength = avgCharsPerWord
    const readabilityScore = Math.max(0, Math.min(100,
      100 - (avgSentenceLength * 2 + avgWordLength * 5)
    ))

    // Structure analysis
    const headings = (text.match(/^#+\s/gm) || []).length
    const lists = (text.match(/^[\s]*[-*+]\s/gm) || []).length +
                  (text.match(/^[\s]*\d+\.\s/gm) || []).length
    const links = (text.match(/https?:\/\/[^\s]+/g) || []).length +
                  (text.match(/\[([^\]]+)\]\(([^)]+)\)/g) || []).length
    const images = (text.match(/!\[([^\]]*)\]\(([^)]+)\)/g) || []).length
    const codeBlocks = (text.match(/```[\s\S]*?```/g) || []).length +
                     (text.match(/`[^`]+`/g) || []).length
    const quotes = (text.match(/^>\s/gm) || []).length

    // Emotion analysis (simplified)
    const positiveWords = /\b(good|great|excellent|amazing|wonderful|fantastic|love|like|enjoy|happy|pleased|satisfied|delighted|thrilled|excited|optimistic|confident|proud|grateful|thankful|blessed|fortunate|lucky|successful|achieved|accomplished|brilliant|outstanding|superb|magnificent|spectacular|incredible|unbelievable|awesome|perfect|flawless)\b/gi
    const negativeWords = /\b(bad|terrible|awful|horrible|disgusting|hate|dislike|sad|angry|frustrated|disappointed|worried|anxious|stressed|depressed|unhappy|miserable-devastated-crushed-destroyed-broken-damaged-harmed-hurt-injured-painful-suffering-difficult-hard-challenging-impossible-unsolvable-problematic-issue-trouble-concern-worry-fear-afraid-sacred-anxious-nervous-tense-stressed-overwhelmed-exhausted-tired-weary-fatigued-drained-burned-out)\b/gi

    const positiveMatches = text.match(positiveWords) || []
    const negativeMatches = text.match(negativeWords) || []
    const totalEmotionWords = positiveMatches.length + negativeMatches.length

    const emotions = {
      positive: totalEmotionWords > 0 ? (positiveMatches.length / totalEmotionWords) * 100 : 60,
      negative: totalEmotionWords > 0 ? (negativeMatches.length / totalEmotionWords) * 100 : 20,
      neutral: totalEmotionWords > 0 ? ((totalEmotionWords - positiveMatches.length - negativeMatches.length) / totalEmotionWords) * 100 : 20
    }

    // Writing time estimation
    const estimatedWritingTime = Math.ceil(wordCount / 20) // 20 WPM average writing speed

    return {
      wordCount,
      characterCount,
      characterCountNoSpaces,
      paragraphCount,
      sentenceCount,
      lineCount,
      readingTime,
      speakingTime,
      complexity: {
        avgWordsPerSentence,
        avgCharsPerWord,
        vocabularySize,
        readabilityScore
      },
      structure: {
        headings,
        lists,
        links,
        images,
        codeBlocks,
        quotes
      },
      emotions,
      writingTime: {
        estimated: estimatedWritingTime
      }
    }
  }

  if (!isOpen || !analytics) return null

  const structureData = [
    { name: 'Headings', value: analytics.structure.headings, color: '#3B82F6' },
    { name: 'Lists', value: analytics.structure.lists, color: '#10B981' },
    { name: 'Links', value: analytics.structure.links, color: '#F59E0B' },
    { name: 'Images', value: analytics.structure.images, color: '#EF4444' },
    { name: 'Code', value: analytics.structure.codeBlocks, color: '#8B5CF6' },
    { name: 'Quotes', value: analytics.structure.quotes, color: '#EC4899' }
  ].filter(item => item.value > 0)

  const emotionData = [
    { name: 'Positive', value: analytics.emotions.positive, color: '#10B981' },
    { name: 'Neutral', value: analytics.emotions.neutral, color: '#6B7280' },
    { name: 'Negative', value: analytics.emotions.negative, color: '#EF4444' }
  ]

  const complexityData = [
    { metric: 'Readability', score: analytics.complexity.readabilityScore, max: 100 },
    { metric: 'Vocabulary', score: Math.min((analytics.complexity.vocabularySize / analytics.wordCount) * 100, 100), max: 100 },
    { metric: 'Sentence Length', score: Math.max(0, 100 - analytics.complexity.avgWordsPerSentence * 2), max: 100 }
  ]

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-6xl h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <div>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Document Analytics</h2>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{title}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500 dark:text-gray-400" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-gray-200 dark:border-gray-700">
          <button
            onClick={() => setActiveTab('overview')}
            className={`px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === 'overview'
                ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
            }`}
          >
            Overview
          </button>
          <button
            onClick={() => setActiveTab('structure')}
            className={`px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === 'structure'
                ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
            }`}
          >
            Structure
          </button>
          <button
            onClick={() => setActiveTab('readability')}
            className={`px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === 'readability'
                ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
            }`}
          >
            Readability
          </button>
          <button
            onClick={() => setActiveTab('trends')}
            className={`px-6 py-3 text-sm font-medium transition-colors ${
              activeTab === 'trends'
                ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
            }`}
          >
            Trends
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {activeTab === 'overview' && (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <FileText className="w-5 h-5 text-blue-600" />
                  <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Words</span>
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {analytics.wordCount.toLocaleString()}
                </div>
              </div>

              <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Clock className="w-5 h-5 text-green-600" />
                  <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Reading Time</span>
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {analytics.readingTime} min
                </div>
              </div>

              <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Type className="w-5 h-5 text-purple-600" />
                  <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Characters</span>
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {analytics.characterCount.toLocaleString()}
                </div>
              </div>

              <div className="bg-orange-50 dark:bg-orange-900/20 p-4 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Hash className="w-5 h-5 text-orange-600" />
                  <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Readability</span>
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {Math.round(analytics.complexity.readabilityScore)}%
                </div>
              </div>
            </div>
          )}

          {activeTab === 'structure' && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Document Structure</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={structureData}
                      cx="50%"
                      cy="50%"
                      outerRadius={80}
                      dataKey="value"
                      label={({ name, value }) => `${name}: ${value}`}
                    >
                      {structureData.map((entry) => (
                        <Cell key={`cell-${entry.name}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </div>

              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Element Details</h3>
                <div className="space-y-3">
                  {structureData.map((item) => (
                    <div key={item.name} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
                        <span className="text-gray-700 dark:text-gray-300">{item.name}</span>
                      </div>
                      <span className="font-medium text-gray-900 dark:text-gray-100">{item.value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'readability' && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Complexity Metrics</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={complexityData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="metric" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="score" fill="#3B82F6" />
                  </BarChart>
                </ResponsiveContainer>
              </div>

              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Writing Analysis</h3>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600 dark:text-gray-400">Avg Words per Sentence</span>
                      <span className="font-medium">{analytics.complexity.avgWordsPerSentence.toFixed(1)}</span>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600 dark:text-gray-400">Avg Characters per Word</span>
                      <span className="font-medium">{analytics.complexity.avgCharsPerWord.toFixed(1)}</span>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600 dark:text-gray-400">Vocabulary Size</span>
                      <span className="font-medium">{analytics.complexity.vocabularySize.toLocaleString()}</span>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600 dark:text-gray-400">Estimated Writing Time</span>
                      <span className="font-medium">{analytics.writingTime.estimated} min</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'trends' && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Emotional Tone</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={emotionData}
                      cx="50%"
                      cy="50%"
                      outerRadius={80}
                      dataKey="value"
                      label={({ name, value }) => `${name}: ${value.toFixed(1)}%`}
                    >
                      {emotionData.map((entry) => (
                        <Cell key={`cell-${entry.name}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </div>

              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Quick Stats</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                      {analytics.paragraphCount}
                    </div>
                    <div className="text-sm text-gray-600 dark:text-gray-400">Paragraphs</div>
                  </div>
                  <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                      {analytics.sentenceCount}
                    </div>
                    <div className="text-sm text-gray-600 dark:text-gray-400">Sentences</div>
                  </div>
                  <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                      {analytics.lineCount}
                    </div>
                    <div className="text-sm text-gray-600 dark:text-gray-400">Lines</div>
                  </div>
                  <div className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                      {analytics.speakingTime} min
                    </div>
                    <div className="text-sm text-gray-600 dark:text-gray-400">Speaking Time</div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default DocumentAnalytics